import 'element-plus/theme-chalk/el-message.css'
import {ElMessage} from 'element-plus'
import {useUserStore} from '@/stores/userStore'
import router from '@/router'
//axios基础的封装
import axios from 'axios'
const httpInstance=axios.create({
  baseURL:'http://pcapi-xiaotuxian-front-devtest.itheima.net',//基地址
  timeout:20000,//超时时间
})

//axios请求拦截器
httpInstance.interceptors.request.use(config=> {
  //1.从pinia中获取token数据
  const userStore=useUserStore()
  const token=userStore.userInfo.token
  if(token){
    config.headers.Authorization=`Bearer ${token}`
  }
  return config;
}, e=> {
  return Promise.reject(e);
});

//axios响应拦截器
httpInstance.interceptors.response.use(response=> {
  return response.data;  //这里返回什么  then(res => res 就是什么)
}, e=>{
  const userStore=useUserStore()
  //统一的错误提示
  ElMessage({
    type:'warning',
    message:e.response.data.message
  })
  //401token失效
  /* 1.清除本地用户数据  2.跳转到登录页面 */
  if(e.response.status===401){
    userStore.clearUserInfo()
    router.push('/login')
  }
  return Promise.reject(e);
});

export default httpInstance
